<template>
  <ele-modal
    :form="true"
    :destroy-on-close="true"
    width="400px"
    v-model="visible"
    title="批量导入、更新学生基础数据"
    :before-close="closeBatchUpload"
  >
    <el-upload
      :limit="1"
      accept=".xlsx, .xls"
      :headers="upload.headers"
      :action="upload.url"
      :disabled="upload.isUploading"
      :before-upload="handleBeforeFileUpload"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="true"
      v-loading="upload.loading"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip text-center" slot="tip">
        <span>仅允许导入xls、xlsx格式文件。</span>
      </div>
    </el-upload>
    <el-link type="primary" style="font-size:13px;vertical-align: baseline;"
             @click="download">下载导入模板
    </el-link>
    <el-divider></el-divider>
    <div style="padding-bottom: 30px;">
      <h3 style="color: #999999;font-size: 14px;">上传进度</h3>
      <el-progress :stroke-width="18" :text-inside="true" :percentage="upload.uploadPercent"></el-progress>
      <h3 style="color: #999999;font-size: 14px;">导入进度</h3>
      <el-progress :stroke-width="18" :text-inside="true" :percentage="upload.importPercent"></el-progress>
    </div>
  </ele-modal>

</template>

<script setup>
import {ref, reactive, watch} from 'vue';
import {EleMessage} from 'ele-admin-plus';
import {useFormData} from '@/utils/use-form-data';
import {
  importStudentInfo,
  importStudentInfoProgress,
  downloadTemplate
} from "@/api/manage/statistic/admin/studentInfo/index.js";
import {getToken} from "@/utils/token-util.js";

const emit = defineEmits(['done']);

/** 弹窗是否打开 */
const visible = defineModel({type: Boolean});

/** 提交状态 */
const loading = ref(false);

/** 关闭弹窗 */
const handleCancel = () => {
  visible.value = false;
}


const upload = reactive({
  // 是否正在上传
  isUploading: false,
  // 是否禁用上传
  isDisable: false,
  // 设置上传的请求头部
  headers: {Authorization: getToken()},
  url: import.meta.env.VITE_API_URL + "/admin/employment/statistic/student/baseInfo/uploadData",
  uploadPercent: 0,
  importPercent: 0,
  loading: false
});

const uploadResult = reactive({
  successNum: 0,
  failureNum: 0,
  countNum: 0,
  resultFileName: ''
});


/** 监听弹窗打开 */
watch(visible, () => {
  if (visible.value) {
    // if (props.data) {
    //   // form.ids = props.data.map(item => item.id);
    // }
  } else {
    // resetFields();
  }
});


const closeBatchImport = () => {

}


const handleBeforeFileUpload = (rawFile) => {
  upload.loading = true;
  upload.isUploading = true;
}


const handleFileUploadProgress = (event, file, fileList) => {
  upload.uploadPercent = (event.loaded / event.total * 100) | 0
  upload.isUploading = true;
}
let handleInterval = null;

const handleFileSuccess = (res, file, fileList) => {
  upload.isUploading = false;
  EleMessage.success({message: "数据上传成功，正在执行导入！", plain: true});
  let data = {fileName: res.msg};
  handleInterval = setInterval(function () {
    importStudentInfoProgress(res.msg).then(res2 => {
      let _percent = parseInt(res2.msg);
      if (!isNaN(_percent)) {
        upload.importPercent = _percent;
      }
    });
  }, 2000);
  importStudentInfo(data).then(res3 => {
    if (handleInterval) {
      clearInterval(handleInterval);
      handleInterval = null;
    }
    //进入到这里面，代表导入结束
    upload.importPercent = 100;
    upload.isUploading = false;
    upload.loading = false;
    EleMessage.success({message: "数据导入成功！", plain: true});
    uploadResult.successNum = res3.data.successNum;
    uploadResult.failureNum = res3.data.failureNum;
    uploadResult.countNum = res3.data.countNum;
    uploadResult.resultFileName = res3.data.resultFileName;
    //TODO 弹出框告知导入结束，并下提供下载文件地址
    // this.resultDialogVisible = true;
  }).catch((e) => {
    upload.isUploading = false;
    EleMessage.error({message: e.message, plain: true});
  });
}

const closeBatchUpload = () => {
  clearInterval(handleInterval);
  handleInterval = null;
}


const download = () => {
  const loading = EleMessage.loading('请求中..');
  downloadTemplate()
    .then(() => {
      loading.close();
    })
    .catch((e) => {
      loading.close();
      EleMessage.error(e.message);
    });
}

</script>
